package com.jxbeidou.gateway.filter;

import com.jxbeidou.core.cache.CacheService;
import com.jxbeidou.core.constents.CacheKeys;
import com.jxbeidou.core.util.JsonUtil;
import com.jxbeidou.gateway.consts.LoginConstants;
import com.jxbeidou.gateway.service.ValidateCodeService;
import com.jxbeidou.gateway.util.ReactiveHttpUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;

import java.nio.CharBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 验证码过滤器
 *
 * @author ruoyi
 */
@Component
@Slf4j
public class ValidateCodeFilter extends AbstractGatewayFilterFactory<AbstractGatewayFilterFactory.NameConfig> {
    @Resource
    private ValidateCodeService validateCodeService;

    @Resource
    private CacheService cacheService;

    private static final String CODE = "code";

    private static final String UUID = "key";

    @Override
    public String name() {
        return "ValidateCodeFilter";
    }

    public ValidateCodeFilter() {
        super(NameConfig.class);
    }

    @Override
    public GatewayFilter apply(NameConfig config) {
        log.debug("[验证码过滤器][{}]", config.getName());
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            if (!StringUtils.equalsAnyIgnoreCase(request.getURI().getPath(), LoginConstants.VALIDATE_URL)) {
                return chain.filter(exchange);
            }
            try {
                String rspStr = resolveBodyFromRequest(request);
                Map<String, String> map = JsonUtil.parseMap(rspStr);
                String code = map.get(CODE);
                String key = map.get(UUID);
                if (StringUtils.isEmpty(code) || StringUtils.isEmpty(key)) {
                    log.warn("[验证码过滤器]验证码为空或验证码校验KEY为空,key:[{}], code:[{}]", key, code);
                    return ReactiveHttpUtil.responseResult(exchange.getResponse(), "验证码不能为空");
                }
                String cacheCode = cacheService.getString(CacheKeys.getCaptchaKey(key));
                if (StringUtils.isEmpty(cacheCode)) {
                    log.warn("[验证码过滤器]缓存中没有找到验证码，验证码已过期");
                    return ReactiveHttpUtil.responseResult(exchange.getResponse(), "验证码已过期");
                }
                if (!StringUtils.equalsIgnoreCase(code, cacheCode)) {
                    log.warn("[验证码过滤器]验证码输入错误, front-code:[{}],server-code:[{}]", code, cacheCode);
                    return ReactiveHttpUtil.responseResult(exchange.getResponse(), "验证码输入错误");
                }
            } catch (Exception e) {
                log.error("[验证码过滤器]JSON转换错误", e.getMessage());
                return ReactiveHttpUtil.responseResult(exchange.getResponse(), e.getMessage());
            }
            return chain.filter(exchange);
        };
    }

    private String resolveBodyFromRequest(ServerHttpRequest serverHttpRequest) {
        // 获取请求体
        Flux<DataBuffer> body = serverHttpRequest.getBody();
        AtomicReference<String> bodyRef = new AtomicReference<>();
        body.subscribe(buffer -> {
            CharBuffer charBuffer = StandardCharsets.UTF_8.decode(buffer.asByteBuffer());
            DataBufferUtils.release(buffer);
            bodyRef.set(charBuffer.toString());
        });
        return bodyRef.get();
    }
}
